
const qiniu = require('qiniu')
const nanoid = require('nanoid')
const config = require('../config')

const bucket = config.qiniu.bucket
const mac = new qiniu.auth.digest.Mac(config.qiniu.AK, config.qiniu.SK)
const cfg = new qiniu.conf.Config()
const client = new qiniu.rs.BucketManager(mac, cfg)

const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')

const uploadToQiniu = async (url, key) => {
  return new Promise((res, rej) => {
    client.fetch(url, bucket, key, (err, ret, info) => {
      if (err) {
        rej(err)
      } else {
        if (info.statusCode === 200) {
          res({ key })
        } else {
          rej(info)
        }
      }
    })
  })
}

;(async () => {
  let movies = await Movie.find({
    // $or: [ { videoKey: { $exists: false } }, { videoKey: null }, { videoKey: '' } ]
    $or: [ { coverKey: { $exists: false } }, { coverKey: null }, { coverKey: '' } ]
  })
  // console.log(movies, '----', movies.length)
  // return 
  movies.forEach(async movie => {
    if (movie.cover && !movie.coverKey) {
      try {
        let posterData = {}
        let videoData = {}
        let coverData = {}
        if (movie.poster) {
          posterData = await uploadToQiniu(movie.poster, nanoid() + '.png')
        }
        if (movie.video) {
          videoData = await uploadToQiniu(movie.video, nanoid() + '.mp4')
        }
        if (movie.cover) {
          coverData = await uploadToQiniu(movie.cover, nanoid() + '.png')
        }
        if (videoData.key) {
          movie.videoKey = videoData.key
        }
        if (coverData.key) {
          movie.coverKey = coverData.key
        }
        if (posterData.key) {
          movie.posterKey = posterData.key
        }
        await movie.save()
      } catch (err) {
        console.log(err)
      }
    }
  })
  console.log('图床上传完毕')
})()
